/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI.SavingBookManager;

import BLL.SavingBook_BLL;
import BLL.Unity;
import DTO.Customer_DTO;
import DTO.SavingBook_DTO;
import DTO.SavingType_DTO;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Nguyen Phi Hung
 */
public class SavingBookManager extends javax.swing.JInternalFrame {

    static String txtMaSo = "";
    static int txt_KyHan;
    Unity unity = new Unity();
    String sql = "select BookID,FullName,IDNumber,TypeName,Term,AccountBalance,OpeningDate,SBStatus\n"
            + "from (SAVINGBOOK inner join CUSTOMER on CUSTOMER.CustomerID=SAVINGBOOK.CustomerID) inner join SAVINGTYPE on SAVINGBOOK.TypeID=SAVINGTYPE.TypeID";
    SavingBook_BLL savingbook_bll = new SavingBook_BLL();
    TableSavingBook model = new TableSavingBook();

    public SavingBookManager() throws Exception {
        initComponents();
        setOpaque(true);
        model.SetTable(Table);
        model.SetData(sql);
        unity.load_combobox(KyHan, "savingtype", "Term");
        unity.load_combobox(TenLoai, "savingtype", "typename");
        NgayMo.setDate(new Date());
        CMND.setDocument(getPlainDocument(11));
    }
    /*
     * set panel
     */
    /*
     * lay ma so tu form quan ly so tiet kiem
     */

    public String MaSo() {
        return MaSo.getText().trim();
    }

    public int KyHan() {

        return Integer.parseInt(KyHan.getSelectedItem().toString());
    }

    public void ReLoadTable(String sql) {
        this.sql = sql;
        model.RemoveData();
        try {
            model.SetData(sql);
        } catch (Exception ex) {
            Logger.getLogger(SavingBookManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static PlainDocument getPlainDocument(final int maxLength) {
        PlainDocument p = new PlainDocument() {
            @Override
            public void insertString(int arg0, String arg1, AttributeSet arg2)
                    throws BadLocationException {
// TODO Auto-generated method stub
                if (getLength() + arg1.length() <= maxLength) {
                    super.insertString(arg0, arg1, arg2);
                }
            }
        };
        return p;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        Table = new org.jdesktop.swingx.JXTable();
        jXPanel1 = new org.jdesktop.swingx.JXPanel();
        jLabel1 = new javax.swing.JLabel();
        HoTen = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        SoTienGui = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        CMND = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        KyHan = new javax.swing.JComboBox();
        TenLoai = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        NgayMo = new org.jdesktop.swingx.JXDatePicker();
        jLabel7 = new javax.swing.JLabel();
        MaSo = new javax.swing.JTextField();
        TrangThai = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        MoSo = new javax.swing.JButton();
        RutTien = new javax.swing.JButton();
        NhapLai = new javax.swing.JButton();
        GuiTien = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        setResizable(true);
        setTitle("Quản lý sổ tiết kiệm");
        setPreferredSize(new java.awt.Dimension(1101, 619));

        Table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(Table);

        jXPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 15)); // NOI18N
        jLabel1.setText("Họ Tên");
        jXPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 60, -1, 28));

        HoTen.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                HoTenKeyTyped(evt);
            }
        });
        jXPanel1.add(HoTen, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 60, 161, 28));

        jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 15)); // NOI18N
        jLabel2.setText("Tên Loại STK");
        jXPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 100, -1, 28));

        SoTienGui.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                SoTienGuiKeyTyped(evt);
            }
        });
        jXPanel1.add(SoTienGui, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 140, 161, 28));

        jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 15)); // NOI18N
        jLabel3.setText("Số Tiền Gửi");
        jXPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 140, -1, 28));

        CMND.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                CMNDKeyTyped(evt);
            }
        });
        jXPanel1.add(CMND, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 60, 161, 28));

        jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 15)); // NOI18N
        jLabel4.setText("CMND");
        jXPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 60, -1, 28));

        jLabel5.setFont(new java.awt.Font("Times New Roman", 0, 15)); // NOI18N
        jLabel5.setText("Kỳ Hạn");
        jXPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 100, -1, 28));

        jXPanel1.add(KyHan, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 100, 160, 28));

        jXPanel1.add(TenLoai, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 100, 161, 28));

        jLabel6.setFont(new java.awt.Font("Times New Roman", 0, 15)); // NOI18N
        jLabel6.setText("Ngày Mở");
        jXPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 140, -1, -1));
        jXPanel1.add(NgayMo, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 140, 160, 30));

        jLabel7.setFont(new java.awt.Font("Times New Roman", 0, 15)); // NOI18N
        jLabel7.setText("Mã Sổ");
        jXPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 20, -1, 28));

        MaSo.setEditable(false);
        jXPanel1.add(MaSo, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 20, 161, 28));

        TrangThai.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Mở", "Đóng" }));
        jXPanel1.add(TrangThai, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 20, 159, 28));

        jLabel8.setFont(new java.awt.Font("Times New Roman", 0, 15)); // NOI18N
        jLabel8.setText("Trạng Thái");
        jXPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 20, -1, 28));

        MoSo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Small_AddCustomer.png"))); // NOI18N
        MoSo.setText("Mở Sổ");
        MoSo.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        MoSo.setIconTextGap(28);
        MoSo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MoSoActionPerformed(evt);
            }
        });
        jXPanel1.add(MoSo, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 30, 180, 40));

        RutTien.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Small_WithdrawBill.png"))); // NOI18N
        RutTien.setText("Rút Tiền");
        RutTien.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        RutTien.setIconTextGap(10);
        RutTien.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RutTienActionPerformed(evt);
            }
        });
        jXPanel1.add(RutTien, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 90, 180, 40));

        NhapLai.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Small_Update.png"))); // NOI18N
        NhapLai.setText("Nhập Lại");
        NhapLai.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        NhapLai.setIconTextGap(28);
        NhapLai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NhapLaiActionPerformed(evt);
            }
        });
        jXPanel1.add(NhapLai, new org.netbeans.lib.awtextra.AbsoluteConstraints(800, 30, 180, 40));

        GuiTien.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Small_DepositBill.png"))); // NOI18N
        GuiTien.setText("Gửi Tiền");
        GuiTien.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        GuiTien.setIconTextGap(10);
        GuiTien.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GuiTienActionPerformed(evt);
            }
        });
        jXPanel1.add(GuiTien, new org.netbeans.lib.awtextra.AbsoluteConstraints(800, 90, 180, 40));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jXPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 990, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jXPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void TableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableMouseClicked
        // TODO add your handling code here:
        int index = Table.getSelectedRow();
        MaSo.setText(Table.getValueAt(index, 0) + "");
        HoTen.setText(Table.getValueAt(index, 1) + "");
        CMND.setText(Table.getValueAt(index, 2) + "");
        TenLoai.setSelectedItem(Table.getValueAt(index, 3));
        KyHan.setSelectedItem(Table.getValueAt(index, 4).toString());
        SoTienGui.setText(Table.getValueAt(index, 5) + "");
        NgayMo.setDate((Date) Table.getValueAt(index, 6));
        TrangThai.setSelectedItem(Table.getValueAt(index, 7));
    }//GEN-LAST:event_TableMouseClicked

    private void MoSoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MoSoActionPerformed
        // TODO add your handling code here:
        /*
         * 
         * kiểm tra họ tên và cmnd của khách hàng có tồn tại trên hệ thống hay chưa. nếu chưa thì đăng ký thông tin,
         * ngược lại thì chuyển sang bước tiếp theo
         * Kiểm tra số tiền khi mở sổ. nếu số tiền khi mở sổ < số tiền gửi tối thiểu thì kết thúc,
         * ngược lại thì chuyển sang bước tiếp theo
         * 
         */
        Customer_DTO info_customer = new Customer_DTO();
        info_customer.setFullName(HoTen.getText().trim());
        info_customer.setIDNumber(CMND.getText().trim());
        SavingBook_DTO info_savingbook = new SavingBook_DTO();
        info_savingbook.setAccountBalance(Float.parseFloat(SoTienGui.getText().trim()));
        info_savingbook.setOpeningDate(unity.ConvertDate(NgayMo));
        SavingType_DTO info_savingtype = new SavingType_DTO();
        info_savingtype.setName(TenLoai.getSelectedItem().toString());
        info_savingtype.setTerm(Integer.parseInt(KyHan.getSelectedItem().toString()));
        try {
            /*
             * kiểm tra
             */
            boolean KiemTraKH = savingbook_bll.KiemTraThongTin_KH("{call Check_Customer(?,?,?)}", info_customer.getFullName(), info_customer.getIDNumber());
            int SoLuongSTK = savingbook_bll.SoLuong_STK("{call Check_SL_STK(?,?,?)}", info_customer.getFullName(), info_customer.getIDNumber());
            boolean SoTienGui = savingbook_bll.KiemTraSoTienGui("{call KiemTra_SoTienGui(?,?)}", info_savingbook.getAccountBalance());

            if (KiemTraKH) {
                if (SoLuongSTK < 5) {
                    if (SoTienGui) {
                        try {
                            savingbook_bll.Insert_Update_Delete("{call Insert_SavingBook(?,?,?,?,?,?)}", info_customer, info_savingbook, info_savingtype);
                            JOptionPane.showMessageDialog(null, "Mở Sổ Thành Công");
                            ReLoadTable(sql);
                        } catch (Exception e) {
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "Số Tiền Gửi Phải Lớn Hơn Số Tiền Gửi Tối Thiểu");
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Không thể Mở Thêm Sổ");
                }
            } else {
                JOptionPane.showMessageDialog(null, "Khách Hàng Chưa Tồn Tại Trên Hệ Thống, Vui Lòng Đăng Ký Thông Tin Cho Khách Hàng");
            }

        } catch (Exception ex) {
            Logger.getLogger(SavingBookManager.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_MoSoActionPerformed

    private void RutTienActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RutTienActionPerformed
        // TODO add your handling code here:
        txtMaSo = this.MaSo();
        txt_KyHan = this.KyHan();
        try {
            JF_WithDraw frame = new JF_WithDraw();
            frame.setVisible(true);
            frame.setLocationRelativeTo(this);
        } catch (Exception ex) {
            Logger.getLogger(SavingBookManager.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_RutTienActionPerformed

    private void NhapLaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NhapLaiActionPerformed
        // TODO add your handling code here:
        MaSo.setText("");
        HoTen.setText("");
        CMND.setText("");
        SoTienGui.setText("0.0");
    }//GEN-LAST:event_NhapLaiActionPerformed

    private void GuiTienActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GuiTienActionPerformed
        // TODO add your handling code here:
        try {
            txtMaSo = this.MaSo();
            JF_Deposit frame = new JF_Deposit();
            frame.setVisible(true);
            frame.setLocationRelativeTo(this);
            
        } catch (Exception e) {
        }
    }//GEN-LAST:event_GuiTienActionPerformed

    private void HoTenKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_HoTenKeyTyped
        // TODO add your handling code here:
        char c = evt.getKeyChar();
        if ((c < 32) || (c > 32 && c < 65) || (90 < c && c < 97) || c > 122) {
            evt.consume();
        }
    }//GEN-LAST:event_HoTenKeyTyped

    private void SoTienGuiKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_SoTienGuiKeyTyped
        // TODO add your handling code here:
        char c = evt.getKeyChar();
        if ((c < 48 || c > 57)) {
            evt.consume();
        }
    }//GEN-LAST:event_SoTienGuiKeyTyped

    private void CMNDKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CMNDKeyTyped
        // TODO add your handling code here:
        char c = evt.getKeyChar();
        if ((c < 48 || c > 57)) {
            evt.consume();
        }
    }//GEN-LAST:event_CMNDKeyTyped
    /**
     * show data by row and column
     *
     * @param row
     * @param col
     */
    /**
     *
     * @param evt
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField CMND;
    private javax.swing.JButton GuiTien;
    private javax.swing.JTextField HoTen;
    private javax.swing.JComboBox KyHan;
    private javax.swing.JTextField MaSo;
    private javax.swing.JButton MoSo;
    private org.jdesktop.swingx.JXDatePicker NgayMo;
    private javax.swing.JButton NhapLai;
    private javax.swing.JButton RutTien;
    private javax.swing.JTextField SoTienGui;
    private org.jdesktop.swingx.JXTable Table;
    private javax.swing.JComboBox TenLoai;
    private javax.swing.JComboBox TrangThai;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane2;
    private org.jdesktop.swingx.JXPanel jXPanel1;
    // End of variables declaration//GEN-END:variables
}
